<template>
  <div class="statistics">
    <div class="box-right">
      <base-map :defaultTools="extendedTools" class="base-map" @close-search="showSearchPanel=false" @search="handleSearch" ref="workmap"
        @tool-change="handleToolChange">
        <template #left-menu>
          <custom-tree :data="treeData" @selection-change="handleSelectionChange" />
        </template>
        <template #right-panel>
          <native-group-table :data="indexData" />
        </template>
        <template #search-bar>
          <search-results-panel :results="searchResults" :visible="showSearchPanel && searchResults.length > 0"
            @close="showSearchPanel = false" @item-click="zoomToFeature" />
        </template>
      </base-map>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator';
import BaseMap from "@/components/Map/BaseMap.vue";
import WorkTree from "@/views/region/components/WorkTree.vue";
import CustomTree from '@/components/Map/CustomTree.vue';
import DataParamMenu from '@/views/app/components/DataParamMenu.vue'
import { userGeoJson } from '@/api/investDataCommon';
import { searchIndex } from '@/api/findData';
import { treeSelectAll } from '@/api/indexCategory';
import NativeGroupTable from '@/components/Map/work/NativeGroupTable.vue';
import SearchResultsPanel from '@/components/Map/work/SearchResultsPanel.vue';

import _ from 'lodash';
import { Getter } from 'vuex-class';

import { selectLocation,defaultLocation } from '@/utils/amap-helper';

declare const AMap: any;
@Component({
  methods: {},
  components: { WorkTree, BaseMap, DataParamMenu, CustomTree, NativeGroupTable, SearchResultsPanel }

})
export default class workData extends Vue {
  @Getter('departInfo') private departInfo!: any;
  @Ref("workmap") workmap;

  private featurePropId = '';
  private geoJsonLayer: any = null;
  debouncedHandleSearch;
  models: any = {
    searchName: '',
    workId: ''
  }
  mapInstance: any = null;

  defaultTools = [
    { name: 'clean', label: '清理', icon: 'clear-icon-32', disabled: false }
  ];

  extendedTools = [
    ...this.defaultTools,
    { name: 'analysis', label: '分析', icon: 'analysis-icon-32', disabled: false }
  ];

  private treeData = [];
  private indexCategoryIds: any = [];
  private indexData: any = [];
  private investData: any;
  private searchResults: Array<{ id: number, name: string, category: string }> = [];
  private showSearchPanel: any = false;
  private allFeatures = [];
  private currentOverlay;

  handleToolChange(toolName: string | null) {
    console.log('当前激活工具:', toolName);
    // 根据工具类型执行不同操作
    switch (toolName) {
      case 'clean':
        this.cleanWorkTool();
        break;
      case 'analysis':
        this.analysisTool();
        break;
    }
  }

  private initDrawInteraction() {
    // 初始化绘图逻辑
    console.log('绘制')

  }

  handlerMarker(properties: any) {
    if (properties.marked) {
      this.$message.info("该要素已标记过");
      return
    }
    console.log(properties)
    this.workmap.createPointFeature(properties.location, properties.name);
    properties.marked = true;

  }

 

  private cleanWorkTool() {
    // 初始化测量逻辑
    console.log('清理工作图层');
  }


  private analysisTool() {

    if (this.indexCategoryIds.length == 0) {
      this.$message.info("请先选择分析指标分类数据");
      return;
    }

    const features = this.workmap.getOverlays();
    if (features.length == 0) {
      this.$message.info("请先绘制范围");
      return;
    }

    const feature = features.find((feature) => feature.type !== 'AMap.Marker'); 

    if(!feature){
      this.$message.info("请先绘制范围");
      return;
    }
    const featurePath = feature.getPath().map((point: any) => [point.lng, point.lat]);

    const inFeatures = this.allFeatures.filter((feature:any) =>{

      switch(feature.geometry.type) {
        case 'Polygon':
          return AMap.GeometryUtil.doesRingRingIntersect(feature.geometry.coordinates,featurePath);
        case 'Point':
          return AMap.GeometryUtil.isPointInRing([feature.geometry.coordinates[0],feature.geometry.coordinates[1]],featurePath);
      }
    });

    console.log('找到图层为',inFeatures)
  
    const ids = inFeatures.map((feature:any) => feature.properties.id.replace('Point',''));


    searchIndex({
      ... this.departInfo,
      indexList: this.indexCategoryIds,
      ids:ids
    }).then(res => {
      this.indexData = res.data;
      if(this.indexData && this.indexData.length > 0) {
        this.workmap.openRightPanel();
        this.$store.dispatch('setIndexData',  this.indexData);

      }else{
        this.$message.info("未找到匹配数据");
      }
    });

  }

  get matchedIndexData() {
    if (!this.featurePropId) return null;

    const rs = this.findAllIndexData(this.featurePropId);
    return rs;
  }


  get findAllIndexData() {
    const data = this.indexData;
    return function (name: string) {
      if (!data) return [];
      const matched = data
        ?.flatMap((cat: any) => cat.data || [])
        ?.filter((item: any) => item.departName == name);

      return matched ? matched : [];
    }
  }


  

  highlightFeature(overlay: any) {
    if (overlay instanceof AMap.Marker) {

      overlay.setIcon(selectLocation);
    } else if (overlay instanceof AMap.Polyline) {
      overlay.setOptions({
        strokeColor: '#ff0000',
        strokeWeight: 5
      });
    } else if (overlay instanceof AMap.Polygon) {
      overlay.setOptions({
        fillColor: 'rgba(255,0,0,0.3)',
        strokeColor: '#ff0000',
        strokeWeight: 3
      });
    }
  }


  // 通过特征点查找对应的覆盖物
  findOverlayByFeature(featureId) {
    let result = null;
    this.geoJsonLayer = this.workmap.getLayerByName('数据图层');
    if (!this.geoJsonLayer) {

      return null;
    }
   
    this.geoJsonLayer.eachOverlay(overlay => {
    let overlayData;
      
    // 区分覆盖物类型 
      if (overlay instanceof AMap.Marker) {
        overlayData = overlay.getExtData(); 
      } else if (overlay instanceof AMap.Polygon) {
         overlayData = overlay.getExtData();  // 获取自定义属性 
      }
     
      if (overlayData && overlayData.id  === featureId) {
        result = overlay;
        return true; // 停止遍历
      }
    });
    return result;
  }


   private zoomToFeature(feature) {

    this.geoJsonLayer = this.workmap.getLayerByName('数据图层');
    if (!this.geoJsonLayer) return;

    // 清除之前的高亮
    this.resetAllFeatures();

    this.currentOverlay = this.findOverlayByFeature(feature.properties.id);
    if (this.currentOverlay) {

      // 高亮显示当前要素
      this.highlightFeature(this.currentOverlay);

      // 定位到要素
      if (this.currentOverlay instanceof AMap.Marker) {
        this.workmap.map.setCenter(this.currentOverlay.getPosition());
        this.workmap.map.setZoom(15);
      } else if(this.currentOverlay instanceof AMap.Polygon) {
        this.workmap.map.setFitView([this.currentOverlay]);
        this.workmap.map.setZoom(15);
      }

      // 显示弹窗

        this.workmap.showPopup(feature, this.currentOverlay);
      
    } else {
      console.error('未找到对应的覆盖物', feature);
    }

  }
  handleSearch(searchKeyword) {
    const keyword = searchKeyword.trim();
    if (!keyword) {
      this.$message.warning("请输入搜索关键词");
      return;
    }

    const dataLayer = this.workmap.getLayerByName('数据图层');
    if (!dataLayer) return;

    // 收集所有要素


    // 执行搜索
    this.searchResults = this.searchGeoJSONFeatures(this.investData, { name: searchKeyword });
    if(!this.searchResults || this.searchResults.length == 0) {
        this.workmap.innerMapSearch();
    }else{
  // 显示结果面板
      this.showSearchPanel = true;
      // 高亮显示结果要素
      this.highlightSearchResults();
       this.$message.success('数据搜索完成');
    }
   

  }

  resetAllFeatures() {
    if (!this.geoJsonLayer) return
    this.geoJsonLayer.eachOverlay(overlay => {
      const feature = overlay.getExtData();
      if (feature) {
        if (overlay instanceof AMap.Marker) {
        
          overlay.setIcon(defaultLocation);
        } else if (overlay instanceof AMap.Polyline) {
          overlay.setOptions({
            strokeColor: '#3388ff',
            strokeWeight: 3
          });
        } else if (overlay instanceof AMap.Polygon) {
          overlay.setOptions({
            fillColor: 'rgba(51,136,255,0.2)',
            strokeColor: '#3388ff',
            strokeWeight: 2
          });
        }
      }
    });
  }

  searchGeoJSONFeatures(geojson, filters) {
    return geojson.features.filter(feature => {
      return Object.entries(filters).every(([key, value]) => {
        // 支持模糊匹配（如名称包含关键字）
        if (typeof value === "string") {
          return feature.properties[key].toLowerCase().includes(value.toLowerCase());
        }
        // 精确匹配（如 ID 或数字类字段）
        return feature.properties[key] === value;
      });
    });
  }


  handleSelect(item) {

    const findIds = this.workmap.findFeature();
    if (findIds.length == 0) {
      this.$message.info("在指定区域内没有找到数据");
      return;
    }

    this.$message.success(`在指定区域内找到${findIds.length}条数据`);

  }

  private handleSelectionChange(selectedIds: number[]) {
    // 处理选中逻辑
    this.indexCategoryIds = selectedIds;

  }

  highlightSearchResults() {
    // 先重置所有特征点样式
    this.resetAllFeatures();
    // 高亮显示搜索结果
    if (!this.searchResults) {
      return;
    }

    this.searchResults.forEach((feature: any) => {
      const overlay: any = this.findOverlayByFeature(feature.properties.id);
      if (overlay) {
        if (overlay instanceof AMap.Marker) {
          // 更换高亮图标
          overlay.setIcon(selectLocation);
        } else if (overlay instanceof AMap.Polyline) {
          overlay.setOptions({
            strokeColor: '#ff0000',
            strokeWeight: 5
          });
        } else if (overlay instanceof AMap.Polygon) {

          overlay.setOptions({
            fillColor: 'rgba(255,0,0,0.3)',
            strokeColor: '#ff0000',
            strokeWeight: 3
          });
        }
      }
    });
  }
  searchAddressHandler(name) {

    if (this.isLatLong(name)) {
      this.workmap.updatePosition(name.split(','))
      return;
    }
    this.workmap.searchFeature(name);

  }

  // 创建高亮标记点
  createHighlightMarker(properties) {
    const name = properties.name || '未命名';
    return `<div class="custom-marker highlight">
        <div class="marker-icon">
          <i class="el-icon-location"></i>
        </div>
        <div class="marker-name">${name}</div>
      </div>`;
  }
  isLatLong(str) {
    const [lat, long] = str.split(',');
    if (isNaN(lat) || isNaN(long)) {
      return false;
    }
    return true;
  }

  startSearch(event) {
    if (event.target.classList.contains('el-input__icon') && this.models.searchName) {
      console.log('后缀图标被点击');
      this.searchAddressHandler(this.models.searchName);
      // 这里写你的点击逻辑
    }

  }
  created() {

    this.debouncedHandleSearch = _.debounce(this.startSearch, 1000);

  }

  extractFeatures() {
    if (!this.investData || !this.investData.features) return;

    this.allFeatures = this.investData.features.map(feature => {
      // 添加可搜索的文本字段
      const searchText = Object.values(feature.properties)
        .filter(val => typeof val === 'string')
        .join(' ')
        .toLowerCase();

      return {
        ...feature,
        searchText
      };
    });
  }

  mounted() {

    setTimeout(() => {
      this.mapInstance = this.workmap.map;

      userGeoJson(this.departInfo).then(res => {
        if (res.data.features.length > 0) {
          this.investData = res.data;
          this.extractFeatures();
          this.workmap.addObjectLayer(res.data, "数据图层", 'green');
          this.geoJsonLayer = this.workmap.getLayerByName('数据图层');
        }
      })
      treeSelectAll({}).then(res => {
        this.treeData = this.normalizeTreeData(res.data);
      });
    }, 200)


  }

  /**
   * 对树形数据进行标准化处理，返回处理后的树形数据
   *
   * @param data 树形数据源
   * @returns 标准化后的树形数据
   */
  private normalizeTreeData(data: any[]) {

    if (!data || data.length === 0) {
      return [];
    }
    return data.map(item => ({
      id: item.id,
      label: item.label,
      level: item.level,
      children: item.children ? this.normalizeTreeData(item.children) : [],
      selected: false,
      expanded: false
    }));
  }


}
</script>
<style lang="scss" scoped>
.statistics {
  display: flex;
  height: 100vh;
  overflow: auto; // 隐藏溢出内容

  .box-left {
    height: auto;
  }

  .box-right {
    flex: 1;
    padding: 0px;
    display: flex;
    flex-direction: column;
    gap: 0px;
    overflow: auto;
  }
}

.boundary-right {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  top: 30px;
  left: 18px;
  z-index: 1000;
}

.boundary-left {
  background-color: #fff;
  opacity: 0.6;
  position: absolute;
  padding: 10px;
  bottom: 0px;
  left: 0px;
  z-index: 1000;
  color: darkgreen;
}

.base-map {
  position: relative;
  height: 100%;

}
</style>
